import {
	http
} from "./luch-request/index.js";

import GC from "../glogal_config.js";

const baseUrl = GC.API_URL;

function getData(response) {
	if (response.code === 200) {
		return response.data;
	} else {
		return response;
	}
}

function checkStatus(response) {
	uni.hideLoading();

	if (response.statusCode >= 200 && response.statusCode <= 300) {
		return response.data;
	}

	return response;

	if (response.status === 400) {
		return response;
	}

	// const errorText = codeMessage[response.status] || response.statusText;

	// if (response.status !== 401) {
	//   notification.error({
	//     message: `请求错误 ${response.status}`,
	//     description: (<Fragment>
	//       {response.url}
	//       <br />
	//       {errorText}
	//     </Fragment>),
	//   });
	// }

	// const error = new Error(errorText);
	// error.name = response.status;
	// error.response = response;
	// throw error;
}

http.setConfig((config) => { /* config 为默认全局配置*/
	config.baseUrl = baseUrl
	config.header = {
		a: 1,
		b: 2
	}
	return config
})

// 测试场景拦截器
http.interceptor.request((config, cancel) => { /* cancel 为函数，如果调用会取消本次请求。需要注意：调用cancel,本次请求的catch仍会执行。必须return config */
	config.header = {
		...config.header,
	}

	// if (process.env.NODE_ENV === 'development') {
	// 	console.log("development env");
	// }

	// if(process.env.NODE_ENV === 'production'){
	// 	console.log("production env");
	// }

	// console.log(config.url)

	return config

})

// request 
export default function request(url, options) {
	uni.showLoading({
		title: "加载中...."
	});

	const defaultOptions = {
		credentials: 'include ----> terry',
	};

	const newOptions = {
		...defaultOptions,
		...options
	};

	if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
		newOptions.headers = {
			Accept: 'application/json',
			'Content-Type': 'application/json; charset=utf-8',
			...newOptions.headers,
		};
		newOptions.data = newOptions.body;
	}

	console.debug('request[' + (newOptions.method !== undefined ? newOptions.method : 'GET') + ']', url);
	return http.request({
		url,
		...newOptions
	})
		.then(checkStatus)
		.then(getData)
		.then(resp => {
			if (resp) {
				if (resp.code === 400) { //这里是经过包装的Response, Status为200，但是Response对象里面包含了status，结果为400.
					// message.error(resp.Msg);
					uni.showToast({
						title: resp.message,
						icon: 'none'
					})

					return;
				}
			}
			return resp;
		});
}

export async function mcRequest(url, waitSeconds = 500) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve(url);
		}, waitSeconds)
	})
}
